/**
* Copyright (c) 2016-2100 yunclouds
*/
package com.yunqian.redot.service;

import com.yunqian.exception.ServiceException;
import com.yunqian.redot.constant.Operation;
import com.yunqian.redot.constant.OperationMenus;
import com.yunqian.redot.constant.ShowStatus;
import com.yunqian.redot.domain.InformationType;
import com.yunqian.redot.repository.InformationTypeRepository;
import com.yunqian.service.BaseService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 咨询分类管理
 *
 * @author zsy
 * 2018-09-29 15:54:40
 */
@Service
@Log4j2
public class InformationTypeService extends BaseService<InformationType, Long> {

    @Autowired
    private InformationTypeRepository informationTypeRepository;
    @Autowired
    private OperationLogService operationLogService;

    public List<InformationType> findAllByOrderBySortNum(){
        return informationTypeRepository.findAllByOrderBySortNum();
    }

    public List<InformationType> getAllByStatusOrderBySortNum(){
        return informationTypeRepository.findAllByStatusOrderBySortNum(ShowStatus.YES.getCode());
    }

    public InformationType getFirstById(Long id){
        return informationTypeRepository.findFirstById(id);
    }

    public InformationType save(InformationType informationType, Long userId) {
        boolean exist = informationTypeRepository.existsByTitle(informationType.getTitle());
        if(exist){
            throw new ServiceException("保存失败，该分类名称已存在");
        }
        super.save(informationType);
        informationType.setAppletUrl("/article/details/" + informationType.getId());
        super.update(informationType);
        operationLogService.save(OperationMenus.NEWS_TYPE, Operation.ADD, userId);
        return informationType;
    }

    public InformationType update(InformationType informationType, Long userId) {
        boolean exist = informationTypeRepository.existsByTitleAndIdNot(informationType.getTitle(), informationType.getId());
        if(exist){
            throw new ServiceException("修改失败，该分类名称已存在");
        }
        InformationType type = super.update(informationType);
        operationLogService.save(OperationMenus.NEWS_TYPE, Operation.UPDATE, userId);
        return type;
    }
}
